﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace dse_pe_parser
{
    public class DailyPeRatiosProviderBiasl: IDailyPeRatiosProvider
    {
        private string _jsonData;

        #region Implementation of IDailyPeRatiosProvider

        public string Name
        {
            get { return "Biasl.net P/E Ratios provider"; }
        }

        public float Version
        {
            get { return 0.01F; }
        }

        public void Prepare()
        {
            //TODO: Implement fetching of the pe ratio page from biasl.net
            _jsonData = File.ReadAllText("biasl.json").Trim();
        }

        public PeRatiosList Fetch()
        {
            var json = JObject.Parse(_jsonData);
            var dataArray = json["data"] as JArray;
            var peList = new PeRatiosList();
            foreach (var data in dataArray)
            {
                DateTime date;
                decimal peLatest, peAudited;
                var symbol = data["compname"].Value<string>().Trim().ToUpperInvariant();
                DateTime.TryParseExact(data["ltdate"].Value<string>().Trim(), GlobalOptions.Instance.CsvDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date);
                decimal.TryParse(data["lpe"].Value<string>().Trim(), out peLatest);
                decimal.TryParse(data["pe"].Value<string>().Trim(), out peAudited);

                // weed out invalid records
                if (!string.IsNullOrEmpty(symbol) && ((peAudited != 0m) || (peLatest != 0m)))
                {
                    peList.AddPeRatio(symbol, date, peLatest, peAudited);
                }
            }
            return peList;
        }

        #endregion
    }
}
